package com.aynu.gulimall.ware.listener;

import com.aynu.common.to.mq.OrderTo;
import com.aynu.common.to.mq.StockLockedTo;
import com.aynu.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author mj
 * @version 1.0
 * @date 2021/4/10 22:06
 */
@Service
@RabbitListener(queues = "stock.release.stock.queue")
@Slf4j
public class StockReleaseListener {

    @Autowired
    private WareSkuService wareSkuService;


    /**
     * 自动解锁库存
     *
     * 存在的问题：如果解锁库存失败，需要多次尝试，但是消息队列中消息自动删除
     * 原因：消息自动应答
     * 解决：取消消息自动应答，改为手动应答
     *
     *
     * @param stockLockedTo
     * @param message
     */
    @RabbitHandler
    public void handStockLockedRelease(StockLockedTo stockLockedTo, Message message,
                                       Channel channel) throws IOException {
        log.info("收到解锁库存的消息,库存工作单详情id:{}，检查是否需要解锁库存",stockLockedTo.getWareTaskId());
        try {
            wareSkuService.unLockStock(stockLockedTo);
            //解锁库存成功，手动应答消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
            //存在异常，则表示解锁失败，需要拒接接受消息，并将消息重新放回消息队列，
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    /**
     * 关单后，解锁库存
     * @param orderTo
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    public void handCloseOrderStockLockedRelease(OrderTo orderTo, Message message,
                                                 Channel channel) throws IOException {
        log.info("订单关单后，准备解锁库存。。。。");
        try {
            wareSkuService.unLockStock(orderTo);
            //解锁库存成功，手动应答消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
            //存在异常，则表示解锁失败，需要拒接接受消息，并将消息重新放回消息队列，
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

}
